package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信小程序后台登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        //1、根据用户授权码换取openid
        String openId = authLogin(userLoginDTO.getCode());

        //2、根据openid判断该用户是否已经存在，不存在需要创建
        User user = this.userMapper.queryByOpenid(openId);
        if(Objects.isNull(user)){
            user = new User();
            BeanUtils.copyProperties(userLoginDTO,user);
            user.setOpenid(openId);
            this.userMapper.save(user);
        }

        //3、根据JWT生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        //4、封装UserLoginVO并返回
        UserLoginVO userLoginVO = UserLoginVO.builder().id(user.getId()).openid(openId).token(token).build();
        return userLoginVO;
    }

    /**
     * 根据授权码换取openid
     * @param code 授权码
     * @return
     */
    private String authLogin(String code) {
        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("appid",weChatProperties.getAppid());
        paramsMap.put("secret",weChatProperties.getSecret());
        paramsMap.put("js_code", code);
        paramsMap.put("grant_type","authorization_code");

        String resultJsonStr = HttpClientUtil.doGet(weChatProperties.getJscode2sessionUrl(), paramsMap);
        JSONObject jsonObject = JSON.parseObject(resultJsonStr);
        String openId = jsonObject.getString("openid");
        if(StringUtils.isEmpty(openId)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return openId;
    }
}
